package hot100.双指针.单行到底.窗口.哈希.会变窗口;

/**
 * 76-最小覆盖子串
 * /**
 * 给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串，则返回空字符串 ""
 * 输入：s = "ADOBECODEBANC", t = "ABC"
 * 输出："BANC"
 * 解释：最小覆盖子串 "BANC" 包含来自字符串 t 的 'A'、'B' 和 'C'。
 */
public class minCoverageSubstring76 {

    public String minWindow(String s, String t) {
        /**
         * todo 哨兵值-抽象推理
         * **/
        int shortestLength = Integer.MAX_VALUE;
        int shortestStart = 0;

        int targetTypeSituation = 0; //字符种类
        int[] targetStatue = new int[128]; //出现次数映射表
        for (int i = 0; i < t.length(); i++) {
            char charTableIndex = t.charAt(i);
            if (targetStatue[charTableIndex] == 0) {
                targetTypeSituation++;
            }
            targetStatue[charTableIndex]++;
        }

        /**head-tail重合表达版(head当前元素索引) 支持开头、结尾识别**/
        int left = 0;
        int nowTypeSituation = 0;
        int[] nowStatue = new int[128];
        for (int right = 0; right < s.length(); right++) {
            nowStatue[s.charAt(right)]++;
            if (nowStatue[s.charAt(right)] == targetStatue[s.charAt(right)]) { nowTypeSituation++;}

            while (nowTypeSituation == targetTypeSituation) {
                //
                /*
                //if (nowStatue[s.charAt(left)] == targetStatue[s.charAt(left)] ) {
                if (nowStatue[s.charAt(left)] >= targetStatue[s.charAt(left)] ) {
                    if ((right - left +1) < shortestLength){
                        shortestLength = right - left +1;
                        shortestStart = left;
                    }
                    nowStatue[s.charAt(left)]--;
                    //只有当窗口中字符数量少于 targetStatue 才减少 nowTypeSituation
                    if (nowStatue[s.charAt(left)] < targetStatue[s.charAt(left)]) {
                        nowTypeSituation--;
                    }
                }
                left++;
                */
                if ((right - left + 1) < shortestLength) {
                    shortestLength = right - left + 1;
                    shortestStart = left;
                }

                nowStatue[s.charAt(left)]--;

                if (nowStatue[s.charAt(left)] < targetStatue[s.charAt(left)]) {
                    nowTypeSituation--;
                }
                left++;
            }

        }

        if (shortestLength == Integer.MAX_VALUE) {return "";}
        return s.substring(shortestStart, shortestStart + shortestLength);

    }

    public static void main(String[] args) {
        minCoverageSubstring76 minCoverageSubstring76 = new minCoverageSubstring76();
        System.out.print(minCoverageSubstring76.minWindow("ADOBECODEBANC", "ABC"));
    }
}